import path from "path";
import { appendFile, checkDirExists, createDirectory, writeToFile } from "../../utils/tools";

interface IParams {
  tableName: string;
  entitesName: string;
  fields: string[];
  superDir: string;
}
export function generModelCode({ tableName, entitesName, fields, superDir }: IParams) {
  const fieldStr = fields
    .map((item: string) => {
      return `${item}: {
      type: DataTypes.STRING,
      allowNull: true,
    }`;
    })
    .join(",");

  const tem = `import sequelize from "../../db/dbConnext";
import { option } from "../../db/commomConfig";
import { DataTypes } from "sequelize";

import ${entitesName}Entity from "../../../entities/${superDir}/${entitesName}Entity";
export type I${entitesName} = Omit<${entitesName}Entity, "validateThis">;

const ${entitesName}Model = sequelize.define<any, I${entitesName}>(
  "${tableName}",
  {
  ${fieldStr}
  },
  option
);
export default ${entitesName}Model;
`;
  return tem;
}

export async function createModel(params: IParams) {
  const codeText = generModelCode(params);
  const filename = params.entitesName + "Model.ts";

  // 1. 找到存放实体文件的目标目录
  const dirPath = path.resolve(__dirname, "../../dao/model", params.superDir);
  if (!(await checkDirExists(dirPath))) {
    await createDirectory(dirPath);
  }

  // 生成实体类文件
  const target = path.resolve(dirPath, filename);
  await writeToFile(target, codeText);

  await appendFile(path.resolve(dirPath, "index.ts"), `import "./${params.entitesName + "Model"}";\n`);
}
